#coding=utf-8
from basehandler import basehandler

__author__ = 'jy@cjlu.edu.cn'
import web
from config import global_lookup
from SysCommon.tools import *
from models.s_user import bll_s_user
from models.s_fun import bll_s_fun
from models.s_ufs import bll_s_ufs

from web.utils import storage
"""
用于处理系统用户权限信息
"""
def Filter(optobj,user_id,recs):
    """
    处理显示数据
    """
    result=[]
    uobj=bll_s_user()
    userobj=uobj.GetRowById(user_id)

    for r in recs:
        t=storage()
        l=(len(r.funno)-2)*2
        t.funno=r.funno
        t.funname="".ljust(l,'-')+str(r.funname)
        if optobj.checkoneuserpower(userobj,r.funno):
            t.checked="checked"
        else:
            t.checked=""
        result.append(t)
    return result
class List(basehandler):
    def get(self):
        i=self.input()
        i.head=i.get('head',"10")
        self.set_header("Content-Type", "text/html; charset=UTF-8")
        funobj=bll_s_fun()
        if i.userid:
            #获取某功能编号头下的所有功能
            recs=funobj.GetFunsByFunHead(i.head)
            recs=Filter(self,i.userid,recs)
            t=global_lookup.get_template("f00/T/userpower_list.html")
            self.write(t.render(datas=recs,userid=i.userid,head=i.head))
        else:
            ShowErrorAndGoBack(u"参数错误")

class Update(basehandler):
    def post(self):
        try:
            self.set_header("Content-Type", "text/html; charset=UTF-8")
            i=self.input()
            i.head=i.get('head',"10")
            funobj=bll_s_fun()
            ufsobj=bll_s_ufs()
            userobj=bll_s_user()
            userentity=userobj.GetRowById(i.userid)

            #清理原有的
            ufsobj.DelUserFuns(i.userid,i.head)
            #找出要授权的
            recs=funobj.GetFunsByFunHead(i.head)
            for r in recs:
                v=i.get("F_"+r.funno,None)
                if v:
                    #保存数据
                    tmpobj=storage()
                    tmpobj.id=0
                    tmpobj.userid=i.userid
                    tmpobj.funno=v
                    ufsobj.Save(tmpobj)
                else:
                    pass
            userobj.Save(userentity)
            #需要更新系统整体的用户权限状态
            funobj=bll_s_fun()
            funobj.refreshPowers()
            #################################################
            self.write(ShowOkMsg("成功","/f00/userpower/list?head="+i.head+"&userid="+i.userid))
        except :
            return ShowErrorAndGoBack("失败")


  